package com.geek.novel.ui;


import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import com.geek.novel.utils.CommUtil;

/**
 * 圆角图片
 * Created by  on 2017/8/22.
 */

public class MyRoundHead extends androidx.appcompat.widget.AppCompatImageView {

    private Paint paint;

    private int strokeWidth;

    public MyRoundHead(Context context, AttributeSet attrs) {
        super(context, attrs);

        init();
    }

    private void init() {
        paint = new Paint();
        this.strokeWidth = (int) CommUtil.INSTANCE.dip2px(3F);
    }

    /**
     * 获取圆形图片方法
     * @param bitmap
     * @return Bitmap
     * @author caizhiming
     */
    private Bitmap getCircleBitmap(Bitmap bitmap) {
        int width = Math.min(bitmap.getWidth(), bitmap.getHeight());
        Bitmap output = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;

        final Rect rect = new Rect(0, 0, width, width);
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        float x = (float) width;
        canvas.drawCircle(x / 2, x / 2, x / 2, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }


    @SuppressLint("DrawAllocation")
    @Override
    protected void onDraw(Canvas canvas) {
        Drawable drawable = getDrawable();
        if(drawable == null){
            super.onDraw(canvas);
            return;
        }

        Bitmap bitmap = getCircleBitmap(((BitmapDrawable) drawable).getBitmap());

        paint.reset();
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);

        paint.setColor(Color.WHITE);
        int x = getWidth();
        canvas.drawCircle(x / 2, x / 2, x / 2, paint);

        final Rect rectSrc = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final Rect rectDest = new Rect(strokeWidth, strokeWidth,getWidth()-strokeWidth, getHeight()-strokeWidth);

        canvas.drawBitmap(bitmap, rectSrc, rectDest, paint);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

}
    
